package com.atguigu.tingshu.order.interceptor.impl;

import com.atguigu.tingshu.common.constant.RedisConstant;
import com.atguigu.tingshu.common.execption.GuiguException;
import com.atguigu.tingshu.common.result.ResultCodeEnum;
import com.atguigu.tingshu.order.interceptor.OrderHandlerInterceptor;
import com.atguigu.tingshu.vo.order.OrderInfoVo;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.script.DefaultRedisScript;
import org.springframework.stereotype.Service;

import java.util.Arrays;

/**
 * 进行表单重复提交的校验
 */
@Service
@Slf4j
public class OrderRepeatSbumitValidOrderHandlerInterceptor implements OrderHandlerInterceptor {

    @Autowired
    private RedisTemplate<String , String> redisTemplate ;

    @Override
    public OrderInfoVo sbumitOrderRequestProcess(OrderInfoVo orderInfoVo) {

        /**
         * 要进行表单重复提交的校验
         */
        String script = "if redis.call(\"exists\",KEYS[1])\n" +
                "then\n" +
                "    return redis.call(\"del\",KEYS[1])\n" +
                "else\n" +
                "    return 0\n" +
                "end" ;
        Long result = redisTemplate.execute(new DefaultRedisScript<Long>(script, Long.class), Arrays.asList(RedisConstant.ORDER_TRADE_NO_PREFIX + orderInfoVo.getTradeNo()));
        if(result.intValue() == 0) {        // 重复提交
            throw new GuiguException(ResultCodeEnum.REPEAT_SUBMIT);
        }
        log.info("表单重复提交校验通过了....");

        return orderInfoVo;
    }

    @Override
    public int sort() {
        return 2;
    }

}
